package db;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

import tlsb.DB;
import tlsb.DBException;
import tlsb.Utils;
import util.IPartition;
import util.RedisCluster;
import util.RedisClusterFactory;

public class RedisClientPUSH extends DB {
	static AtomicLong midCounter = new AtomicLong(0);
	final private long STARTOFFSET = 0;
	final private long ENDOFFSET = 19;
	final private String SETOFFOLLOWERS = ":flr";
	final private String PREFIXOFHID = "sh:";
	// final private String UIDOFMID = ""

	static Random random = new Random();
	private RedisCluster folRedisCluster = RedisClusterFactory.instance
			.getFolRedisCluster();
	private RedisCluster statusRedisCluster = RedisClusterFactory.instance
			.getStatusRedisCluster();

	private boolean _Debug = false;

	public void init() throws DBException {

	}

	public void cleanup() throws DBException {
		folRedisCluster.close();
		statusRedisCluster.close();
	}

	@Override
	public int follow(String uid, String fid) {
		// TODO Auto-generated method stub
		// add to new followers and followers for different strateges; also
		// update owns(first) and belongs
		return 0;
	}

	@Override
	// TODO uid change string into integer.
	public int getHTL(String uid, int start) {
		// get all related stls
		// System.err.println("get htl"+uid+"\t cid:"+CGA.hashByCid(uid));
		List<String> htl = statusRedisCluster.getJedis(
				statusRedisCluster.getPartition().shard(uid)).lrange(
				Utils.joinStr(PREFIXOFHID, uid), STARTOFFSET, ENDOFFSET);
		// System.err.println("got htl");
		if (htl == null || htl.size() == 0) {
			// System.err.println("no htl");
		}
		// for(String s:htl)
		// System.err.println(s);
		if (_Debug) {
			// System.out.println(uid + " PUSH:" + htl);
		}
		return 0;
	}

	@Override
	public int newUser() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int post(String uid, String mid) {
		// TODO Auto-generated method stub
		// get the followers of uid
		for (String f : folRedisCluster.getJedis(
				folRedisCluster.getPartition().shard(uid)).smembers(
				Utils.joinStr(uid, SETOFFOLLOWERS))) {
			statusRedisCluster.getPipeline(
					statusRedisCluster.getPartition().shard(f)).lpush(
					Utils.joinStr(PREFIXOFHID, f), mid);
			midCounter.incrementAndGet();
			// System.err.println("midcounter:"+midCounter.get());

			if (midCounter.get() % 1000000 == 0)
				System.err.println(midCounter.get());
		}
		statusRedisCluster.synAllPipelines();
		return 0;
	}

	@Override
	public int unfollow(String uid, String fid) {
		// TODO Auto-generated method stub
		return 0;
	}

}
